<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class MemberWithdraw extends Controller {
    static protected $err_code = 0;

    // 获取提现页面数据
    static public function withdraw_index($param) {
        if(!isset($param['member_id']) || !isset($param['type'])){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        try {
            $models = ['member', 'repair', 'dealer', 'partner'];
            $model = $models[$param['type']];
            
            if ($param['type'] == 0) {
                $where['id'] = $param['member_id'];
                $where['status'] = 1; // 正常状态
                $member = db($model)->field('phone, money, is_certification')->where($where)->find();
            } else {
                $where['member_id'] = $param['member_id'];
                $where['audit_status'] = ($param['type'] == 3 ? 2 : 4); // 正常状态
                $member = db($model)->alias('obj')->field('m.phone, obj.money, obj.is_certification')
                    ->join('mob_member m', 'm.id = obj.member_id')
                    ->where($where)->find();
            }
            // 先获取用户角色数据
            if (!$member) {
                self::$err_code = 400029;
                throw new \Exception('FAULT');
            }

            // 获取银行卡列表
            $fund_account = db('member_fund_account')->where('member_id', $param['member_id'])->select();
//            foreach ($fund_account as $k => $v) {
//                $fund_account[$k]['account'] = str_repeat(str_repeat('*', 4) . ' ', 3) . substr($v['account'], -4);
//            }

            return ['code' => 200, 'data' => ['member' => $member, 'fund_account' => $fund_account], 'msg' =>'success'];
        }catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    
    //用户申请提现接口
    static public function member_withdraw($param) {
        if( !isset($param['member_id']) || !isset($param['fund_account']) || !isset($param['fund_account_type']) || !isset($param['fund_account_id'])
            || !isset($param['money']) || !isset($param['code']) || !isset($param['type']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            if (!$param['fund_account']) {
                self::$err_code = 400142;
                throw new \Exception('FAULT');
            }
            // 获取用户手机号码
            $phone = Db::table('mob_member')->where('id', $param['member_id'])->value('phone');

            // 验证短信验证码是否有效
            $check_code = check_note_code($param['code'], $phone, 1);
            if($check_code['code'] != 200) {
                self::$err_code = $check_code['code'];
                throw new \Exception('FAULT');
            }

            $models = ['member', 'repair', 'dealer', 'partner'];
            $model = $models[$param['type']];

            if ($param['type'] == 0) {
                $where['id'] = $param['member_id'];
                $where['status'] = 1; // 正常状态
            } else {
                $where['member_id'] = $param['member_id'];
                $where['audit_status'] = 4; // 正常状态
            }

            $sum_money = $param['money'] + $param['withdraw_poundage']; // 总扣款金额  提现金额加手续费

            $obj = Db::table('mob_' . $model)->field('money, is_certification')->where($where)->find();
            // 检查是否实名认证
            if ($obj['is_certification'] != 2) {
                self::$err_code = 400119;
                throw new \Exception('FAULT');
            }

            $money = $obj['money'];
            if( $money < $sum_money){
                self::$err_code = 400040;
                throw new \Exception('FAULT');
            }

            // 根据 用户ID 收款账户ID 收款账户 检查收款帐号是否存在
            $member_fund_account = Db::table('mob_member_fund_account')
                ->where('member_id', $param['member_id'])
                ->where('id', $param['fund_account_id'])
                ->where('account', $param['fund_account'])->find();
            if (!$member_fund_account) {
                self::$err_code = 400092;
                throw new \Exception('FAULT');
            }

            Db::table('mob_' . $model)->where($where)->setDec('money', $sum_money);  // 从对应的角色帐号余额上减去提现金额
            Db::table('mob_' . $model)->where($where)->setInc('money_frozen', $sum_money);  // 从对应的角色帐号冻结金额上加上提现金额

            // 添加提现记录
            $withdraw_sn = date('YmdHis') . rand(10000, 99999);
            $data = [
                'member_id' => $param['member_id'],
                'money' => $param['money'],
                'status' => 0,
                'fund_account' => $param['fund_account'],
                'fund_account_type' => $param['fund_account_type'],
                'type' => $param['type'],
                'withdraw_poundage' => $param['withdraw_poundage'],
                'withdraw_sn' => $withdraw_sn,
                'add_time' => time()
            ];
            Db::table('mob_member_withdraw')->insert($data);

            // 在用户账单表添加记录  冻结状态为1  当后台确认时  用户角色 记录 减去对应的冻结金额   同时根据提现单号将账单记录冻结状态改为0
            $member_money_data = [
                'member_id' => $param['member_id']
                ,'order_sn' => $withdraw_sn
                ,'money' => $param['money'] //账单金额
                ,'frozen_status' => 1
                ,'type' => $param['type']
                ,'msg' => "申请提现"
                ,'source' => 6
                ,'add_time' => time()
                ,'pay_type' => '余额提现' // 交易方式
            ];
            Db::table('mob_member_money')->insert($member_money_data);

            // 添加手续费记录
            $member_money_data = [
                'member_id' => $param['member_id']
                ,'order_sn' => $withdraw_sn
                ,'money' => $param['withdraw_poundage'] //账单金额
                ,'frozen_status' => 1
                ,'type' => $param['type']
                ,'msg' => "提现手续费"
                ,'source' => 6
                ,'add_time' => time()
                ,'pay_type' => '余额提现' // 交易方式
            ];
            Db::table('mob_member_money')->insert($member_money_data);

            // 提交事务
            Db::commit();
            return ['code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取用户提现记录接口
    static public function member_withdraw_list($param){
        if(!isset($param['member_id']) || !isset($param['member_role'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try {
            $where = [
                'member_id' => $param['member_id']
            ];
            if ($param['member_role'] > 0) {
                $where['member_role'] = $param['member_role'];
            }
            $member_withdraw = Db::table('mob_member_withdraw')->where($where)->select();
            return ['data' => $member_withdraw, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 分销收益转入可用余额
    static public function distribution_of_cash_money($param) {
        if(!isset($param['member_id']) || !isset($param['type'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try {
            // 获取用户分销金额
            $member = Db::table('mob_member')->field('distribution_money')->where('id', $param['member_id'])->find();

            // 分销余额字段减去分销金额  用户余额字段增加分销金额
            Db::table('mob_member')->where('id', $param['member_id'])->setDec('distribution_money', $member['distribution_money']);

            $models = ['member', 'repair', 'dealer', 'partner'];
            $model = $models[$param['type']];
            if ($param['type'] == 0) {
                $where['id'] = $param['member_id'];
            } else {
                $where['member_id'] = $param['member_id'];
            }
            Db::table('mob_' . $model)->where($where)->setInc('money', $member['distribution_money']);

            // 添加账单
            $data = [
                [
                    'member_id' => $param['member_id']
                    ,'money' => $member['distribution_money']
                    ,'frozen_status' => 0
                    ,'type' => $param['type']
                    ,'msg' => "分销收益兑换至余额"
                    ,'source' => 10  // 分销收益兑换至余额
                    ,'add_time' => time()
                    ,'pay_type' => '分销收益兑换' // 交易方式
                ]
            ];
            Db::table('mob_member_money')->insertAll($data);
            Db::commit();
            return ['data'=>'','code'=>200,'msg'=> 'SUCCESS'];
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }
}
